#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2024/3/6 14:08
# @Author  : jiangwei
# @Site    : 
# @File    : run_check.py
# @Software: PyCharm
import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from pipeline.spider_sql import ShopeeMySqlDB
from utils.send_feishu import send_notice
from utils.trans_date import get_year_month_day, get_yesterday


def check_temu_xmen_success(store_code, sql_obj):
    """
    检查是否已经入库
    :param store_code:
    :param sql_obj:
    :return:
    """
    date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S').split(" ")[0]
    res = sql_obj.query_xmen_count(date=date, store_code=store_code)
    res_record = sql_obj.query_goods_record(date=date, platform="temu_seller_xmen", store_code=store_code)
    count_detail = (len(res))
    count_record = res_record[0][-1] if res_record else 0
    print(date, store_code, count_detail, count_record)
    if (count_detail < count_record) or count_detail == 0:
        return False
    return True


def check_temu_xmen_and_picture():
    """
    检查数据量
    :return:
    """
    date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S').split(" ")[0]
    content = ""
    temu_shop = ["4594954014482", "634418209736233", "634418212290849", "634418217868223", "634418224572421"]
    sql_obj = ShopeeMySqlDB()

    for mall_id in temu_shop:
        has_sql = check_temu_xmen_success(store_code=mall_id, sql_obj=sql_obj)
        xmen = sql_obj.query_xmen_count(date=date, store_code=mall_id)
        if not has_sql:
            content += "temu-xmen-api {} 执行异常; \n".format(mall_id)
        else:
            content += "temu-xmen-api {} 成功，数据量：{} \n".format(mall_id, len(xmen))

    print(content)
    send_notice(content=content)
    sql_obj.close()


def check_shein_seller_count():
    """
    检查shein_seller数据量
    :return:
    """
    content = ""
    sql_obj = ShopeeMySqlDB()
    shop_list = ["US_SN1_CB", "US_SN2_CB"]
    date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S').split(" ")[0]
    table_name = ["shein_seller_sub_order_new", "shein_seller_inventory", "shein_seller_day_detail"]
    for shop in shop_list:
        for table in table_name:
            date = date if table_name == "shein_seller_sub_order_new" else (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
            has_sql = sql_obj.query_shein_seller_count(date=date, table=table, shop=shop)

            # 2025.9.28 部分店铺本身没数据
            if has_sql:
                # print("{}-{}-{}已经有数据。".format(date, shop, table))
                content += "{} {} {} 采集数据量：{}。\n".format(date, shop, table, has_sql)

            else:
                content += "{}-{}-{} 采集数据量为0。\n".format(date, shop, table)


    sql_obj.close()
    print(content)
    # send_user(content=content)
    send_notice(content=content)


def format_notice(platform):
    """
    监控消息对应给数据量纬度指标为spu还是skc
    :param platform:
    :return:
    """
    notice = "spu"
    if platform == "shein" or platform == "shein-pt" or platform == "shein-es":
        notice = "sku"
    elif "temu" in platform:
        notice = "skc"

    return notice


def check_platform_count(platform="shein", sql_obj=None, store_code=None):
    """
    检查shein数据量与temu的数据量并监控
    :return:
    """
    if not sql_obj:
        sql_obj = ShopeeMySqlDB()

    date = get_year_month_day()
    res = sql_obj.query_goods_count(date=date, platform=platform, store_code=store_code)
    res_record = sql_obj.query_goods_record(date=date, platform="temu_buyer" if platform == "temu" else platform,
                                            store_code=store_code)
    count_detail = res[0][3] if (
                                            platform == "shein" or platform == "temu" or platform == "aliexpress" or platform == "shein-pt" or platform == "shein-es") and res else (
        len(res))
    count_record = res_record[0][-1] if res_record else 0

    count_record = count_detail if platform == "aliexpress" and count_record == 0 else count_record

    if res and res_record:
        content = "日期：{}，平台：{}，店铺：{}，商品数量：{}, 入库{}数量：{}".format(res[0][0], platform, res[0][2], res_record[0][-1],
                                                                format_notice(platform), count_detail)
        if platform in ["shein", "shein-pt"]:
            count_record = 0
        content = content if count_detail >= count_record else content + "\n" + "【{}价格监控】-{}-采集异常，请排查".format(platform,
                                                                                                              date)
    else:
        content = "【{} {}-{}价格监控】采集异常，请排查".format(platform, "卖家" if platform == "temu_seller" else "买家", store_code)

    if platform == "aliexpress" and count_detail:
        content = "日期：{}，平台：{}，店铺：{}，商品数量：{}, 入库{}数量：{}".format(date, platform, "1102843818", count_detail, "spu",
                                                                count_detail)

    return content


def check_count():
    """
    检查temu与shopee数据量     temu 4594954014482 是主店   temu 634418209736233 是子店
    :return:
    """
    sql_obj = ShopeeMySqlDB()
    temu_seller_main_content = check_platform_count(platform="temu_seller", sql_obj=sql_obj, store_code="4594954014482")
    temu_seller_sub_content = check_platform_count(platform="temu_seller", sql_obj=sql_obj,
                                                   store_code="634418209736233")
    temu_seller_new_content = check_platform_count(platform="temu_seller", sql_obj=sql_obj,
                                                   store_code="634418212290849")

    content = temu_seller_main_content + ";\n" + temu_seller_sub_content + ";\n" + temu_seller_new_content + ";\n"
    print(content)
    send_notice(content=content)
    sql_obj.close()


def check_aliexpress_seller():
    """
    速卖通  卖家报表数据
    :return:
    """
    w = ShopeeMySqlDB()
    date = get_yesterday(days=1)
    count_sku = w.query_aliexpress_seller_count(table="aliexpress_seller_sku_sale", date=date)
    count_bind = w.query_aliexpress_seller_count(table="aliexpress_seller_bind", date=date)
    content = "速卖通销售管理-销量统计：附表2入库：{}\n速卖通商品管理-商货绑定：入库：{}".format(count_sku, count_bind)
    if count_sku == 0 or count_bind == 0:
        content += "\n数据有异常，请开发排查....."

    print(content)
    send_notice(content=content)

    w.close()


scheduler = BlockingScheduler(job_defaults={'misfire_grace_time': 15 * 60})
# 爬虫采集
scheduler.add_job(func=check_temu_xmen_and_picture, trigger='cron', day="*/1", hour="9", minute="40",
                  timezone='Asia/Shanghai')  # 每天定时执行采集
scheduler.add_job(func=check_shein_seller_count, trigger='cron', day="*/1", hour="8", minute="55",
                  timezone='Asia/Shanghai')  # 每天定时执行采集
# # 监控结果
scheduler.add_job(func=check_count, trigger='cron', day="*/1", hour="9", minute="00",
                  timezone='Asia/Shanghai')  # 每天定时执行采集
scheduler.add_job(func=check_aliexpress_seller, trigger='cron', day="*/1", hour="17", minute="00",
                  timezone='Asia/Shanghai')  # 每天定时执行采集

scheduler.start()
